package pingpongdojo.context.actions;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IActionDelegate;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;

import pingpongdojo.ingame.InGameView;
import pingpongdojo.model.Game;
import pingpongdojo.model.ModelFactory;

public class AddToGameAction implements IObjectActionDelegate {

	// private Shell shell;
	private IFile selectedFile;

	public AddToGameAction() {
		super();
	}

	/**
	 * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
	 */
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		// shell = targetPart.getSite().getShell();
	}

	/**
	 * @see IActionDelegate#run(IAction)
	 */
	public void run(IAction action) {
		Game currentGame = ModelFactory.getInstance().getGameManager()
				.getCurrentGame();

		if (currentGame != null) {
			currentGame.addFile(selectedFile);

			ModelFactory.getInstance().getGameManager().fireGameUpdateEvent();
		} else {
			MessageDialog.openInformation(PlatformUI.getWorkbench()
					.getActiveWorkbenchWindow().getShell(),
					"PingPongDojo", InGameView.NO_GAME_IN_PROGRESS_MSG);
		}
	}

	/**
	 * @see IActionDelegate#selectionChanged(IAction, ISelection)
	 */
	public void selectionChanged(IAction action, ISelection selection) {

		if (selection instanceof IStructuredSelection) {
			IStructuredSelection ssel = (IStructuredSelection) selection;
			Object obj = ssel.getFirstElement();
			if(obj == null) {
				return;
			}
			IFile file = (IFile) Platform.getAdapterManager().getAdapter(obj,
					IFile.class);
			if (file == null) {
				if (obj instanceof IAdaptable) {
					file = (IFile) ((IAdaptable) obj).getAdapter(IFile.class);
				}
			}
			if (file != null) {
				this.selectedFile = file;
			}
		}
	}

}
